package com.tc.vms.utils;


import com.tc.vms.log.VmsClientLogger;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by yonghua.zhang on 2016/1/23.
 */
public class VmsThreadFactory implements ThreadFactory {
    private final static AtomicLong threadIndex = new AtomicLong(0);
    private final String threadNamePrefix;

    public VmsThreadFactory(final String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        String suffix = "";
        try {
            suffix = String.valueOf(System.currentTimeMillis());
            suffix = suffix.substring(suffix.length() - 3);
        } catch (Exception e) {
        }

        Thread t = new Thread(r, threadNamePrefix + "_" + this.threadIndex.incrementAndGet() + "_" + suffix);

        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                VmsClientLogger.getLog().error("uncaughtException in thread:{}", t.getName(), e);
            }
        });
        return t;

    }
}
